<template>
  <div>
    <div class="search_box search_head" style="margin-bottom: 18px">
      <el-radio-group
        v-model="formData.type"
        @change="handleGroup(formData.type)"
      >
        <el-radio-button :label="1">汇 总</el-radio-button>
        <el-radio-button :label="2">区分小程序</el-radio-button>
      </el-radio-group>
      <selectMultiple
        v-if="formData.type === 2"
        style="margin-left: 18px"
        ref="multAppsSelectRef"
        @selectChange="selectAppsChange"
        :placehText="'小程序'"
        :options="appsOptions"
      />
    </div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formData"
        :label-width="75"
      >
        <el-form-item label="推广时间">
          <selectDate ref="dateRef" type="daterange" @returnTime="returnTime" />
        </el-form-item>
        <el-form-item label="剧集列表">
          <t-select
            placeholder="请选择"
            v-model="formData.operaIds"
            :optionSource="operaOptions"
            labelCustom="label"
            valueCustom="value"
            @current-change="currentSelectChange"
            isShowPagination
            multiple
            collapse-tags
            collapse-tags-tooltip
            :paginationOption="paginationOption"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="getList(1)"
            v-auth="'api:agent:report:operaList'"
          >
            查 询
          </el-button>
          <el-button @click="resetList" v-auth="'api:agent:report:operaList'">
            重 置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <el-button
        type="primary"
        class="export_box"
        @click="getList(9)"
        :loading="loadingExport"
      >
        数据导出
      </el-button>
      <custom-table
        ref="tableRef"
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        @sortChange="sortChange"
        :isCustomHead="true"
        class="table_box"
      >
        <template #date="{ scope }">
          <span v-if="scope.row?.date">
            {{ moment(scope.row?.date + "Z").format("YYYY-MM-DD") }}
          </span>
        </template>
      </custom-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import customTable from "@/components/CustomTable/index.vue";
import { getOperaList } from "@/api/chart/index";
import { movieList } from "@/api/episodeList/index";
import { getAppList } from "@/api/globalManage/appletRoute/index";
import { getAppsList } from "@/api/auth/index";
import selectDate from "@/components/SeleteDate/index.vue";
import moment from "moment";
import { exportTable } from "@/utils/tools";

const dateRef = ref();
const tableRef = ref();
let startT: number = new Date().getTime() - 3600000 * 24 * 6;
const loading = ref<boolean>(false);
const form = reactive({
  type: 1,
  pageNo: 1,
  pageSize: 10,
  start: moment(startT).startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  end: moment().startOf("day").format("YYYY-MM-DDTHH:mm:ss"),
  sorting: "", // asc  desc
  operaIds: [],
  miniAppIds: [],
});
const formData = ref(Object.assign({}, form));
const valueTime = ref<any>("");
const tableData = ref<Array<any>>([]);
const operaOptions = ref<Array<any>>([]);
const appsOptions = ref<Array<any>>([]);
const multAppsSelectRef = ref();
const loadingExport = ref(false);

interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});
const paginationOption = ref({
  pageSize: 7, // 每页显示条数
  currentPage: 1, // 当前页
  pagerCount: 5, // 按钮数，超过时会折叠
  total: 0, // 总条数
});

const columns = reactive([
  { label: "日期", prop: "date", slotName: "date", minWidth: 100 },
  { label: "小程序名称", prop: "miniAppName", minWidth: 100, hidden: true },
  { label: "剧ID", prop: "operaId", minWidth: 80 },
  { label: "剧名", prop: "operaName", minWidth: 100 },
  { label: "总集数", prop: "episodes", minWidth: 70 },
  { label: "播放集数 ", prop: "playEpisodes", minWidth: 80 },
  { label: "播放人数", prop: "playUsers", minWidth: 80 },
  {
    label: "充值金额(元)",
    prop: "rechargeAmount",
    sortable: true,
    minWidth: 130,
    formatter: (row: any) => {
      return `¥${row?.rechargeAmount}`;
    },
  },
  { label: "充值次数", prop: "rechargeTimes", minWidth: 80 },
  { label: "充值人数", prop: "rechargeUsers", minWidth: 80 },
  {
    label: "充值率",
    prop: "rechargeRate",
    minWidth: 80,
    formatter: (row: any) => {
      return `${row?.rechargeRate}%`;
    },
  },
  { label: "充值用户arppu", prop: "rechargeUsersARPU", minWidth: 120 },
  { label: "金币消费集数", prop: "consumeCoinEpisodes", minWidth: 110 },
  { label: "消费金币总数", prop: "consumeCoinTotal", minWidth: 110 },
  { label: "金币消费人数 ", prop: "consumeCoinUsers", minWidth: 110 },
  { label: "人均消费金币数", prop: "consumeCoinAverage", minWidth: 122 },
  {
    label: "人均金币消费集数",
    prop: "consumeCoinEpisodesAverage",
    minWidth: 136,
  },
]);

// 切换汇总 / 小程序
const handleGroup = (val: number | string) => {
  tableRef.value.columnsData = columns.map((item: any) => {
    // 根据type（1 、 2）类型，显示影藏列
    if (val === 1 && item.prop === "miniAppName") {
      item.hidden = true;
    } else {
      item.hidden = false;
    }
    return item;
  });
  getList(1);
};

const selectAppsChange = (val: any) => {
  formData.value.miniAppIds = val;
};

// 重置
const resetList = () => {
  // form.type = formData.value.type;
  // form.miniAppIds = formData.value.miniAppIds;
  formData.value = Object.assign(formData.value, form);
  // 重置组件多选
  if (formData.value.type == 2) {
    multAppsSelectRef.value.multipleData = [];
  }
  dateRef.value.dateValue = [form.start, form.end];
  getList(1);
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = val && val === 9 ? 1 : pageObj.pageNo;
  formData.value.pageSize = val && val === 9 ? 100000 : pageObj.pageSize;

  // 数据导出不刷新列表
  if (val !== 9) {
    loading.value = true;
  } else {
    loadingExport.value = true;
  }
  getOperaList(formData.value)
    .then((res: Record<string, any>) => {
      // 数据导出 中断后续数据渲染
      if (val === 9) {
        exportTable(res?.data, columns, "看剧统计");
        loadingExport.value = false;
        return;
      }

      tableData.value = res.data;
      pageObj.total = Number(res?.total);
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 排序
const sortChange = (val: Record<string, any>) => {
  if (val?.order === "descending") {
    formData.value.sorting = "rechargeAmount desc";
  } else if (val?.order === "ascending") {
    formData.value.sorting = "rechargeAmount asc";
  } else {
    formData.value.sorting = "";
  }
  getList(1);
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

// 切换剧集分页
const currentSelectChange = (val: any) => {
  getMovieList(val);
};

// 获取剧集
const getMovieList = (val = 0) => {
  let params = {
    pageNo: val || paginationOption.value.currentPage,
    pageSize: paginationOption.value.pageSize,
  };
  movieList(params).then((res: Record<string, any>) => {
    operaOptions.value = res.data.map((item: Record<string, any>) => {
      return {
        label: `${item.id} - ${item.name}`,
        value: item?.id,
      };
    });
    paginationOption.value.total = res.total;
  });
};

// 获取小程序
const getApps = () => {
  getAppsList().then((res: any) => {
    appsOptions.value = res.map((item: Record<string, any>) => {
      return {
        label: item.appName,
        value: item?.id.toString(),
        appType: item?.appType,
      };
    });
  });
  // getAppList({ pageNo: 1, pageSize: 1000 }).then((res: Record<string, any>) => {
  //   appsOptions.value = res.data.map((item: Record<string, any>) => {
  //     return {
  //       label: item.appName,
  //       value: item?.id.toString(),
  //       appType: item?.appType,
  //     };
  //   });
  // });
};

// 返回时间
const returnTime = (val: any) => {
  valueTime.value = val;
  formData.value.start = valueTime.value[0];
  formData.value.end = valueTime.value[1];
};

onMounted(() => {
  getList();
  getMovieList();
  getApps();
});
</script>

<style lang="scss" scoped>
.search_head {
  display: flex;
  align-items: center;
}

.table_box_wrapper {
  margin-top: 15px;
  background-color: #fff;
  border-radius: 4px;

  .export_box {
    margin: 10px 0 0 10px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    img {
      width: 72px;
      height: 108px;
      margin-right: 8px;
    }

    span {
      flex: 1;
    }
  }
}
</style>
